package com.yunkaweilai.android.activity.shop;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.SwitchCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.bilibili.boxing.model.entity.impl.ImageMedia;
import com.bilibili.boxing.utils.ImageCompressor;
import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.CaptureActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.model.CodeMsgBean;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.ImageUploadModel;
import com.yunkaweilai.android.model.SimpleModel;
import com.yunkaweilai.android.model.shop.CompanyTypeModel;
import com.yunkaweilai.android.model.shop.ShopInfoDiyModel;
import com.yunkaweilai.android.net.Glide.GlideUtils;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.CharacterParser;
import com.yunkaweilai.android.utils.ImageUtilsK;
import com.yunkaweilai.android.utils.InputMethodUtils;
import com.yunkaweilai.android.utils.PicturePickerHelper;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.shop.ShopCodeSingleDialog;
import com.yunkaweilai.android.view.dialog.shop.ShopInfoImageDelDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.listeners.OnSingleWheelListener;
import cn.addapp.pickers.picker.DatePicker;
import cn.addapp.pickers.picker.SinglePicker;
import okhttp3.Call;

import static com.yunkaweilai.android.utils.ImageUtilsK.deleteSingleFile;

/**
 * 新增普通商品
 * Created by Administrator on 2017/6/14.
 */

public class AddPtShopActivity extends BaseActivity {


    public int SHOP_TYPE_CODE = 101;//分类
    public int SHOP_QR_CODE = 102;//二维码
    public int SHOP_COMPANY_CODE = 103;//单位
    public int IMG_SELECTION = 104;//图片上传
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.id_tv_type_type)
    TextView idTvTypeType;
    @BindView(R.id.id_tv_shop_type)
    TextView idTvShopType;
    @BindView(R.id.id_img_type)
    ImageView idImgType;
    @BindView(R.id.id_tv_code_type)
    TextView idTvCodeType;
    @BindView(R.id.id_edt_code_num)
    EditText idEdtCodeNum;
    @BindView(R.id.id_img_code)
    ImageView idImgCode;
    @BindView(R.id.id_tv_name_type)
    TextView idTvNameType;
    @BindView(R.id.id_edt_good_name)
    EditText idEdtGoodName;
    @BindView(R.id.id_tv_simple_code_type)
    TextView idTvSimpleCodeType;
    @BindView(R.id.id_tv_good_simple_code)
    TextView idTvGoodSimpleCode;
    @BindView(R.id.id_tv_company_type)
    TextView idTvCompanyType;
    @BindView(R.id.id_tv_company)
    TextView idTvCompany;
    @BindView(R.id.id_img_company)
    ImageView idImgCompany;
    @BindView(R.id.id_llayout_diy)
    LinearLayout idLlayoutDiy;
    @BindView(R.id.id_tv_sell_type)
    TextView idTvSellType;
    @BindView(R.id.id_tv_sell_price)
    EditText idTvSellPrice;
    @BindView(R.id.id_tv_purchase_price)
    EditText idTvPurchasePrice;
    @BindView(R.id.id_rlayout_purchase)
    RelativeLayout idRlayoutPurchase;
    @BindView(R.id.id_views)
    View idViews;
    @BindView(R.id.id_tv_kucun)
    TextView idTvKucun;
    @BindView(R.id.id_edt_stock)
    EditText idEdtStock;
    @BindView(R.id.id_rlayout_stock)
    RelativeLayout idRlayoutStock;
    @BindView(R.id.id_view_kucun)
    View idViewKucun;
    @BindView(R.id.id_tv_warning)
    TextView idTvWarning;
    @BindView(R.id.id_edt_warning)
    EditText idEdtWarning;
    @BindView(R.id.id_rlayout_warning)
    RelativeLayout idRlayoutWarning;
    @BindView(R.id.id_view_warning)
    View idViewWarning;
    @BindView(R.id.id_tv_commission)
    TextView idTvCommission;
    @BindView(R.id.id_edt_commission)
    EditText idEdtCommission;
    @BindView(R.id.id_rlayout_commission)
    RelativeLayout idRlayoutCommission;
    @BindView(R.id.id_switch_fixed_discount)
    SwitchCompat idSwitchFixedDiscount;
    @BindView(R.id.id_edt_fixed_discount)
    EditText idEdtFixedDiscount;
    @BindView(R.id.id_switch_fold)
    SwitchCompat idSwitchFold;
    @BindView(R.id.id_llayout_fold)
    LinearLayout idLlayoutFold;
    @BindView(R.id.id_view_fold)
    View idViewFold;
    @BindView(R.id.id_switch_integral)
    SwitchCompat idSwitchIntegral;
    @BindView(R.id.id_edt_fixed_integral)
    EditText idEdtFixedIntegral;
    @BindView(R.id.id_llayout_special)
    LinearLayout idLlayoutSpecial;
    @BindView(R.id.id_edt_remark)
    EditText idEdtRemark;
    @BindView(R.id.id_rlayout_remark)
    RelativeLayout idRlayoutRemark;
    @BindView(R.id.id_view_remark)
    View idViewRemark;
    @BindView(R.id.id_img_add1)
    ImageView idImgAdd1;
    @BindView(R.id.id_img_del)
    ImageView idImgDel;
    @BindView(R.id.content_view)
    ScrollView contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_switch_qiyong)
    Switch mSwitch;
    @BindView(R.id.id_tv_add_tel)
    TextView mTextViewtel;

    private Gson gson = new Gson();
    private String goods_category_id = "";//分类id
    private String unit = "";//单位id
    private String is_special_discount = "0";//是否启用特殊折扣
    private String is_discount_to_discount = "0";//是否开启折上折
    private String is_special_points = "0";//是否是特殊积分
    private String mPicPath = "";//文件路径
    private String upload_img_url = "";
    private boolean isSingleCode = false;
    private ShopCodeSingleDialog dialog;
    private ArrayList<ShopInfoDiyModel.DataBean.InfoBean> diyList = new ArrayList<>();
    private Map<String, String> diymap = new HashMap<>();
    private LayoutInflater inflater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_shop2);
        ButterKnife.bind(this);
        new TitleBuilder(this).setLeftImage(R.mipmap.ic_go_back)
                .setTitleText("新增商品")
                .setRightText("保存");
        inflater = this.getLayoutInflater();
        idMultipleStatusView.showLoading();
        idLlayoutSpecial.setVisibility(View.GONE);
        mSwitch.setChecked(true);//默认启用商品
        initDate();
        initClick();
        getShopDiy();
        setunit();
    }

    //设置默认单位第一个
    private void setunit() {
        HttpRequest.postUrl(Api.COMPANY_TYPE_LIST)
                .log(TAG).execute(new PostProcess.StringCallBack() {
            @Override
            public void onResponse(String json) {
                Gson gson = new Gson();
                boolean checkCode = Utils.checkCode(mAc, json);
                if (checkCode) {
                    CompanyTypeModel companyTypeModel = gson.fromJson(json, CompanyTypeModel.class);
                    if (companyTypeModel.getData().getList().size() > 0) {
                        idTvCompany.setText(companyTypeModel.getData().getList().get(0).getUnit_name());
                        idTvCompany.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                        unit = companyTypeModel.getData().getList().get(0).getId() + "";
                    }
                } else {
                }
            }

            @Override
            public void onError(Exception e) {
            }
        });
    }

    //获取商品自定义属性
    private void getShopDiy() {
        HttpRequest.postUrl(Api.SHOP_DIY_LIST)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            ShopInfoDiyModel shopInfoDiyModel = gson.fromJson(json, ShopInfoDiyModel.class);
                            initAddView(shopInfoDiyModel);
                        }
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showContent();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showContent();
                        }
                    }
                });
    }

    //处理自定义属性
    private void initAddView(ShopInfoDiyModel shopInfoDiyModel) {
        diyList.clear();
        diyList.addAll(shopInfoDiyModel.getData().getInfo());
        for (int i = 0; i < diyList.size(); i++) {
            ShopInfoDiyModel.DataBean.InfoBean listBean = diyList.get(i);
            LinearLayout view = null;
            if ("text".equals(listBean.getField_type())) {
                view = (LinearLayout) inflater
                        .inflate(R.layout.view_member_diy_edt, null);
                diyEdts(i, view);
            } else if ("select_time".equals(listBean.getField_type())) {
                view = (LinearLayout) inflater
                        .inflate(R.layout.view_member_diy_txt, null);
                diyTimes(i, view);
            } else if ("radio".equals(listBean.getField_type())) {
                view = (LinearLayout) inflater
                        .inflate(R.layout.view_member_diy_txt, null);
                diyRadio(i, view);
            } else if ("checkbox".equals(listBean.getField_type())) {
                view = (LinearLayout) inflater
                        .inflate(R.layout.view_member_diy_txt, null);
                diyCheck(i, view);
            }
            idLlayoutDiy.addView(view);
        }
        if (diyList.size() == 0) {
            idLlayoutDiy.setVisibility(View.GONE);
        } else {
            idLlayoutDiy.setVisibility(View.VISIBLE);
        }
    }

    //自动生成编码
    private void getBM() {
        HttpRequest.postUrl(Api.APP_CREATE_SKU)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(mAc,json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            SimpleModel simpleModel = gson.fromJson(json, SimpleModel.class);
                            idEdtCodeNum.setText(simpleModel.getData().getSku());
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    private void initClick() {
        mTextViewtel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBM();
            }
        });
        idEdtCommission.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                int posDot = temp.indexOf(".");
                if (posDot <= 0) return;
                if (temp.length() - posDot - 1 > 2) {
                    s.delete(posDot + 3, posDot + 4);
                }
            }
        });

        //销售价格  限制2位小数
        idTvSellPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                int posDot = temp.indexOf(".");
                if (posDot <= 0) return;
                if (temp.length() - posDot - 1 > 2) {
                    s.delete(posDot + 3, posDot + 4);
                }
            }
        });

        //进货价格  限制2位小数
        idTvPurchasePrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                int posDot = temp.indexOf(".");
                if (posDot <= 0) return;
                if (temp.length() - posDot - 1 > 2) {
                    s.delete(posDot + 3, posDot + 4);
                }
            }
        });
        //商品名称生成简称
        idEdtGoodName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String convert = CharacterParser.getInstance().getSelling(s + "");
                idTvGoodSimpleCode.setText(convert);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        //商品名称点击时，验证条码唯一性
        idEdtGoodName.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (!isSingleCode) {
                        if (!StringUtils.isEmpty(idEdtCodeNum.getText().toString())) {
                            checkCode();
                        }
                    }
                }
                return false;
            }
        });

        idEdtCodeNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isSingleCode = false;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    //检验是否存在
    private void checkCode() {
        HttpRequest.postUrl(Api.CHECK_CODE_SINGLE)
                .addParams("sku", idEdtCodeNum.getText().toString())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json, true);
                        if (checkCode) {
                            dialog = new ShopCodeSingleDialog(mAc, "存在相同条码,请重输");
                            dialog.show();
                        } else {
                            isSingleCode = true;
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 101:
                    String typeID = data.getStringExtra(ShopTypeActivity.SHOP_TYPE_ID);
                    String typeName = data.getStringExtra(ShopTypeActivity.SHOP_TYPE_NAME);
                    if (StringUtils.isEmpty(typeID)) {

                    } else {
                        idTvShopType.setText(typeName);
                        idTvShopType.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                        goods_category_id = typeID;
                    }
                    break;
                case 102:
                    //处理扫描结果（在界面上显示）
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        String result = bundle.getString(CaptureActivity.RESULT);
                        idEdtCodeNum.setText(result);
                    }
                    break;
                case 103://单位处理
                    String unitID = data.getStringExtra(CompanyTypeActivity1.UNITID);
                    String unitName = data.getStringExtra(CompanyTypeActivity1.UNIT_NAME);
                    idTvCompany.setText(unitName);
                    idTvCompany.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                    unit = unitID + "";
                    break;
                case 104://图片上传
                    final ArrayList<BaseMedia> medias = Boxing.getResult(data);
                    BaseMedia baseMedia = medias.get(0);
                    if (!(baseMedia instanceof ImageMedia)) {
                        return;
                    }
                    showProgressDialog("请稍等，图片上传中...");
                    final ImageMedia imageMedia = (ImageMedia) baseMedia;
                    //对返回的图片进行压缩
                    if (imageMedia.compress(new ImageCompressor(this))) {
                        imageMedia.removeExif();
                    }
                    //压缩质量和尺寸 上面这个不靠谱
                    File fileDir = Environment.getExternalStorageDirectory();
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    Bitmap bitmap = BitmapFactory.decodeFile(imageMedia.getPath(), opts);// 文件路径
                    ImageUtilsK.compressImage2FileBySize(bitmap, new File(fileDir, "ptshop.jpg"));
                    File file1 = new File(fileDir, "ptshop.jpg");
                    mPicPath = file1.getAbsolutePath();

//                    mPicPath = imageMedia.getPath();
                    uploadFile(mPicPath);
                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    String uri = PicturePickerHelper.onPickLogoOrAvatarActivityResult(requestCode, resultCode, data);
                    if (!StringUtils.isEmpty(uri)) {
                        uploadFile(uri);
                    } else {
                        showToast("未选择照片");
                    }
                    break;

            }
        }
    }

    //文件上传
    private void uploadFile(final String mPicPath) {
        Map<String, String> paprms = new HashMap<>();
        paprms.put("token", BaseApplication.getToken());
        OkHttpUtils.post().addFile("file", "shop.jpg", new File(mPicPath))
                .url(Api.IMAGE_UPLOAD).params(paprms).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        showToast("上传失败");
                        deleteSingleFile(mPicPath);
                    }
                });
            }

            @Override
            public void onResponse(final String response, int id) {

                boolean isChecked = Utils.checkCode(AddPtShopActivity.this, response);
                if (!isChecked) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissProgressDialog();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            GlideUtils.loadImage(AddPtShopActivity.this, new File(mPicPath), idImgAdd1);
//                            Log.d(TAG, "run: " + mPicPath);
                            idImgDel.setVisibility(View.VISIBLE);
                            dismissProgressDialog();
                            ImageUploadModel imageUploadModel = gson.fromJson(response, ImageUploadModel.class);
                            upload_img_url = imageUploadModel.getData().getPath();
                            GlideUtils.loadImage(mAc, upload_img_url, idImgAdd1);
                            PictureFileUtils.deleteCacheDirFile(AddPtShopActivity.this);
                        }
                    });
                }
                deleteSingleFile(mPicPath);
            }
        });

    }

    //上传图片删除
    public void setImages() {
        GlideUtils.loadGlideImage(mAc, R.mipmap.ic_image_add, idImgAdd1);
//        idImgAdd1.setBackgroundResource(R.mipmap.ic_image_add);
        idImgDel.setVisibility(View.GONE);
        upload_img_url = "";
    }

    @OnClick({R.id.id_img_del, R.id.titlebar_iv_left, R.id.titlebar_tv_right, R.id.id_tv_shop_type, R.id.id_img_type, R.id.id_img_code, R.id.id_tv_company, R.id.id_img_company, R.id.id_img_add1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_img_del://删除图片
                ShopInfoImageDelDialog dialogs = new ShopInfoImageDelDialog(mAc, ShopInfoImageDelDialog.ADDPTSHOP);
                dialogs.show();

                break;
            case R.id.titlebar_iv_left:
                InputMethodUtils.closeSoftKeyboard(mAc);
                finish();
                break;
            case R.id.id_tv_shop_type:
            case R.id.id_img_type://分类
                Intent intent = new Intent(this, ShopTypeActivity.class);
                intent.putExtra(ShopTypeActivity.SHOP_TYPE_URL, Api.SHOP_TYPE_LIST);
                intent.putExtra(ShopTypeActivity.SHOP_TYPE, ShopTypeActivity.PT_SHOP);
                startActivityForResult(intent, SHOP_TYPE_CODE);
                break;
            case R.id.id_img_code://条码
                getCameraManifest();
                break;
            case R.id.id_tv_company:
            case R.id.id_img_company://单位
                startActivityForResult(new Intent(this, CompanyTypeActivity1.class), SHOP_COMPANY_CODE);
                break;
            case R.id.id_img_add1://添加图片
//                String cachePath = BoxingFileHelper.getCacheDir(this);
//                if (TextUtils.isEmpty(cachePath)) {
//                    Toast.makeText(this, R.string.storage_deny, Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                Uri destUri = new Uri.Builder()
//                        .scheme("file")
//                        .appendPath(cachePath)
//                        .appendPath(String.format(Locale.US, "%s.jpg", System.currentTimeMillis()))
//                        .build();
//                BoxingConfig singleCropImgConfig = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).withCropOption(new BoxingCropOption(destUri).aspectRatio(1, 1)).needCamera();
//                Boxing.of(singleCropImgConfig).withIntent(this, PhotoPickerActivity.class).start(this, IMG_SELECTION);
                PicturePickerHelper.pickLogoOrAvatar(AddPtShopActivity.this);
                break;
            case R.id.titlebar_tv_right://保存
                httpIsRight();
                break;
        }
    }

    //参数验证
    private void httpIsRight() {
        if (StringUtils.isEmpty(goods_category_id)) {
            showToast("未选取分类");
            return;
        }
        if (StringUtils.isEmpty(idEdtCodeNum.getText().toString())) {
            showToast("未填写编码");
            return;
        }
        if (StringUtils.isEmpty(idEdtGoodName.getText().toString())) {
            showToast("未填写名称");
            return;
        }
        if (StringUtils.isEmpty(unit)) {
            showToast("未选取单位");
            return;
        }
        if (StringUtils.isEmpty(idTvSellPrice.getText().toString())) {
            showToast("未填写销售价格");
            return;
        }
        if (StringUtils.isEmpty(idEdtStock.getText().toString())) {
            showToast("未填写库存");
            return;
        }
        if (StringUtils.isEmpty(idEdtWarning.getText().toString())) {
            showToast("未填写预警值");
            return;
        }
        if ("1".equals(is_special_discount)) {
            if (StringUtils.isEmpty(idEdtFixedDiscount.getText().toString())) {
                showToast("还未填写折扣");
                return;
            } else {
                if (Integer.parseInt(idEdtFixedDiscount.getText().toString()) < 0 || Integer.parseInt(idEdtFixedDiscount.getText().toString()) > 100) {
                    showToast("折扣范围0-100");
                    return;
                }
            }
        }
        if ("1".equals(is_special_points) && StringUtils.isEmpty(idEdtFixedIntegral.getText().toString())) {
            showToast("还未填写积分");
            return;
        }

        showProgressDialog("请稍等，数据保存中...");
        saveShopInfo();//保存商品信息
    }


    //保存商品信息
    private void saveShopInfo() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String putTime = formatter.format(curDate);
        PostProcess postProcess = HttpRequest.postUrl(Api.PT_SHOP_INFO_SAVE)
                .addParams("goods_category_id", goods_category_id + "").addParams("goods_name", idEdtGoodName.getText().toString())
                .addParams("goods_sku", idEdtCodeNum.getText().toString()).addParams("unit", unit)
                .addParams("goods_purchase_price", idTvPurchasePrice.getText().toString())
                .addParams("goods_shop_price", idTvSellPrice.getText().toString())
                .addParams("goods_stock", idEdtStock.getText().toString())
                .addParams("put_time", putTime)
                .addParams("is_special_discount", is_special_discount)
                .addParams("special_discount", idEdtFixedDiscount.getText().toString())
                .addParams("is_discount_to_discount", is_discount_to_discount)
                .addParams("is_special_points", is_special_points)
                .addParams("special_points", idEdtFixedIntegral.getText().toString())
                .addParams("goods_image", upload_img_url)
                .addParams("goods_warning", idEdtWarning.getText().toString())
                .addParams("goods_reward", StringUtils.isEmpty(idEdtCommission.getText().toString()) ? "0" : idEdtCommission.getText().toString())
                .addParams("status", mSwitch.isChecked() ? "1" : "0");
        Iterator iter = diymap.entrySet().iterator();//自定义字段
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String val = (String) entry.getValue();
            postProcess.addParams(key, val);
        }
        postProcess.execute(new PostProcess.StringCallBack() {
            @Override
            public void onResponse(final String json) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_LIST_REFRESH, true));
                            CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
                            showToast(codeMsgBean.getMessage() + "");
                            finish();
                        } else {
                            showToast("添加商品失败");
                        }

                    }
                });
            }

            @Override
            public void onError(Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        showToast("添加商品失败");
                    }
                });
            }
        });
    }

    //获取照相机权限
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1;

    private void getCameraManifest() {
        MPermissions.requestPermissions(this, MY_PERMISSIONS_REQUEST_CAMERA, Manifest.permission.CAMERA);
    }

    private void getCamera() {
        Intent intent = new Intent(mAc, CaptureActivity.class);
        startActivityForResult(intent, SHOP_QR_CODE);
    }

    @PermissionGrant(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestSuccess() {
        getCamera();
    }

    @PermissionDenied(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestError() {
        showToast("授权失败！");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }


    //处理diy文本信息
    private void diyEdts(final int position, LinearLayout view) {
        ((TextView) view.findViewById(R.id.id_tv_name)).setText(diyList.get(position).getField_name());
        EditText edtContent = (EditText) view.findViewById(R.id.id_edt_content);
        edtContent.setTag(position);
        edtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                diymap.put("DIYField[" + diyList.get(position).getId() + "]", s.toString() + "");
            }
        });

    }

    //时间
    private int mYear;
    private int mMonth;
    private int mDay;

    private void initDate() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mYear = c.get(Calendar.YEAR);// 获取当前年份
        mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
    }

    //diy时间选择
    private void diyTimes(int position, LinearLayout view) {
        ((TextView) view.findViewById(R.id.id_tv_name)).setText(diyList.get(position).getField_name());
        final TextView idTvContent = (TextView) view.findViewById(R.id.id_tv_content);
        idTvContent.setTag(position);
        idTvContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                final DatePicker picker = new DatePicker(mAc);
                picker.setCanLoop(false);
                picker.setWheelModeEnable(true);
                picker.setTopPadding(15);
                picker.setRangeStart(1930, 1, 01);
                picker.setRangeEnd(mYear + 100, 11, 11);
                picker.setSelectedItem(mYear, mMonth, mDay);
                picker.setWeightEnable(true);
                picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        int tag = (int) v.getTag();
                        LinearLayout childAt = (LinearLayout) idLlayoutDiy.getChildAt(tag);
                        TextView viewById = (TextView) childAt.findViewById(R.id.id_tv_content);
                        viewById.setText(year + "-" + month + "-" + day);
                        viewById.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                        diymap.put("DIYField[" + diyList.get(tag).getId() + "]", year + "-" + month + "-" + day);
                    }
                });
                picker.setOnWheelListener(new DatePicker.OnWheelListener() {
                    @Override
                    public void onYearWheeled(int index, String year) {
                        picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onMonthWheeled(int index, String month) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onDayWheeled(int index, String day) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
                    }
                });
                picker.show();
            }
        });
    }

    //diy单选
    private void diyRadio(final int position, LinearLayout view) {
        ((TextView) view.findViewById(R.id.id_tv_name)).setText(diyList.get(position).getField_name());
        final TextView idTvContent = (TextView) view.findViewById(R.id.id_tv_content);
        idTvContent.setTag(position);
        idTvContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tag = (int) v.getTag();
                initPickerSingle(diyList.get(tag).getField_contents(), tag);
            }
        });
    }

    //单选处理
    private void initPickerSingle(List<String> list, final int position) {
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(0);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {


            }
        });
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                LinearLayout childAt = (LinearLayout) idLlayoutDiy.getChildAt(position);
                TextView viewById = (TextView) childAt.findViewById(R.id.id_tv_content);
                viewById.setText(item);
                viewById.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                diymap.put("DIYField[" + diyList.get(position).getId() + "]", item);
            }
        });
        picker.show();
    }

    private void diyCheck(int position, LinearLayout view) {
        ((TextView) view.findViewById(R.id.id_tv_name)).setText(diyList.get(position).getField_name());
        final TextView idTvContent = (TextView) view.findViewById(R.id.id_tv_content);
        idTvContent.setTag(position);
        idTvContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tag = (int) v.getTag();
                checkboxSelector(diyList.get(tag).getField_contents(), tag);
            }
        });
    }

    //处理多选
    private void checkboxSelector(final ArrayList<String> list, final int position) {
        new MaterialDialog.Builder(this)
                .items(list)
                .itemsCallbackMultiChoice(
                        new Integer[]{}, new MaterialDialog.ListCallbackMultiChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text) {
                                return which.length < 8;
                            }
                        })
                .positiveText("确定")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        Integer[] selectedIndices = dialog.getSelectedIndices();
                        for (int i = 0; i < 15; i++) {
                            diymap.remove("DIYField[" + diyList.get(position).getId() + "][" + i + "]");
                        }
                        String selector = "";
                        for (int i = 0; i < selectedIndices.length; i++) {
                            if (i != 0) {
                                selector = selector + ",";
                            }
                            selector = selector + list.get(selectedIndices[i]);
                            diymap.put("DIYField[" + diyList.get(position).getId() + "][" + selectedIndices[i] + "]", list.get(selectedIndices[i]));
                        }
                        LinearLayout childAt = (LinearLayout) idLlayoutDiy.getChildAt(position);
                        TextView viewById = (TextView) childAt.findViewById(R.id.id_tv_content);
                        viewById.setText(selector);
                        viewById.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                    }
                })
                .neutralText("取消")
                .onNeutral(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .alwaysCallMultiChoiceCallback() // the callback will always be called, to check if (un)selection is still allowed
                .show();
    }

}
